import 'dart:convert';
import 'dart:isolate';

import 'package:flutter/material.dart';
import 'package:hi_flutter/app_page.dart';
import 'package:http/http.dart' as http;

class IsolateApp extends StatefulWidget {
  const IsolateApp({Key? key}) : super(key: key);

  @override
  State<IsolateApp> createState() => IsolateAppState();
}

class IsolateAppState extends State<IsolateApp> {
  List postsList = [];

  @override
  void initState() {
    super.initState();
    loadData();
  }

  @override
  Widget build(BuildContext context) {
    return AppPage(
      body: postsList.isEmpty
          ? const CircularProgressIndicator()
          : ListView.builder(
              itemCount: postsList.length,
              itemBuilder: (BuildContext context, int position) {
                return ListTile(
                  title: Text(postsList[position]["title"]),
                  subtitle: Text(postsList[position]["body"]),
                );
              },
            ),
    );
  }

  Future<void> loadData() async {
    ReceivePort receivePort = ReceivePort();
    await Isolate.spawn(dataLoader, receivePort.sendPort);

    SendPort sendPort = await receivePort.first;
    List msg = await sendReceive(
      sendPort,
      "https://jsonplaceholder.typicode.com/posts",
    );

    setState(() {
      postsList = msg;
    });
  }

  static Future<void> dataLoader(SendPort sendPort) async {
    ReceivePort port = ReceivePort();
    sendPort.send(port.sendPort);
    await for (var msg in port) {
      String data = msg[0];
      SendPort replyTo = msg[1];
      String dataURL = data;
      http.Response response = await http.get(Uri.parse(dataURL));
      replyTo.send(jsonDecode(response.body));
    }
  }

  Future sendReceive(SendPort port, msg) {
    ReceivePort response = ReceivePort();
    port.send([msg, response.sendPort]);
    return response.first;
  }
}
